package com.hhit.yb.compose_demo.views.state

import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.hhit.yb.compose_demo.views.StyleableTutorialText
import com.hhit.yb.compose_demo.views.getRandomColor

@Composable
fun Tutorial4_2_7Screen(){
    Column {
        StyleableTutorialText(
            text = "Reading unstable types inside lambda causes function " +
                    "to be recomposed.",
            bullets = false
        )
        Spacer(modifier = Modifier.height(20.dp))
        LambdaStabilitySample()
    }
}


@Preview
@Composable
private fun LambdaStabilitySample() {
    var counter by remember {
        mutableIntStateOf(0)
    }

    val contextWrapper = ContextWrapper(LocalContext.current)
    // 🔥List and Context are not stable, when they are read inside lambda
    // recomposition is triggered in Outer composable
    val context = LocalContext.current
    val list = remember {
        List(5){
            it
        }
    }

    Column {
        Text(text = "Counter $counter")
        Outer {
            counter++
            contextWrapper.context
            context
            list
            Toast.makeText(contextWrapper.context, "Toast", Toast.LENGTH_SHORT).show()
        }
    }
}

// Removing this annotation causes recomposition to be triggered when read
@Immutable
data class ContextWrapper(val context: Context)

@Composable
private fun Outer(
    onClick: () -> Unit
) {

    SideEffect {
        println("Outer")
    }

    Column(
        modifier = Modifier
            .border(2.dp, getRandomColor())
            .padding(10.dp)
    ) {
        Button(onClick = onClick) {
            Text(text = "Click")
        }
    }
}
